package com.gqr.collections;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 组合操作并不保证线程安全
 */
public class OptionsNotSafe implements Runnable {
    private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<String, Integer>();

    public static void main(String[] args) throws InterruptedException {
        scores.put("小明", 0);
        OptionsNotSafe r = new OptionsNotSafe();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);

        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(scores);
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            while (true){
                // scores.get scores.put 是没问题的
                Integer score = scores.get("小明");
                // 问题出现在这里
                int newScore = score + 1;
//            scores.put("小明", newScore);

                // 可以使用replace完成这个操作  不需要额外使用synchronized代码块
                boolean b = scores.replace("小明", score, newScore);
                if(b){
                    break;
                }

                // 还有个类似的 putIfAbsent
//                if(!map.containsKey(key)){
//                    return map.put(key,value)
//                }else{
//                    return map.get(key)
//                }
            }


        }
    }
}
